/*
Copyright (C) Ariff Ehsan, Abdul Hadi Fikri

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/*  Author : Abdul Hadi Fikri
 *  Date   : June 24, 2009
 */


#include <system.h>
/*Button status enumeration*/
enum{
	BS_PUSHED = 0,
	BS_PUSHING,
	BS_RELEASED,
	BS_RELEASING,
};

/*Button status variable*/
uint8_t app_button_state;

/*Timer instantiation*/
timer_t app_timer_button;

/*Task instantiation*/
task_t app_task_button;

/*Prototype function*/
void APP_TIMER_BUTTON_expired(void);
void APP_TASK_BUTTON_run(void);

void APP_booted(){
	/*Initialize button status*/
	app_button_state = BS_RELEASED;
	
	/*Configure PB0 as input pin*/
	CLR_BIT(DDRB,PB0);
	
	/*Configure PORTC as ouput*/
	DDRC = 0xFF;
	
	/*Register timer and task*/
	TASK_reg(&app_task_button,APP_TASK_BUTTON_run);
	TIMER_reg(&app_timer_button,APP_TIMER_BUTTON_expired);
	
	/*Start polling button status*/
	TASK_post(&app_task_button);
}

void APP_TIMER_BUTTON_expired(void){
	switch(app_button_state){
		case BS_RELEASING:
			app_button_state = BS_RELEASED;
		break;
		case BS_PUSHING:
			app_button_state = BS_PUSHED;
			PORTC = ~PORTC;
		break;
	}
	TASK_post(&app_task_button);
}

void APP_TASK_BUTTON_run(void){
	switch(app_button_state){
		case BS_RELEASED:
			if(READ_BIT(PINB,PB0)==0){
				app_button_state = BS_PUSHING;
				TIMER_start(&app_timer_button,20);
			}
			else{
				TASK_post(&app_task_button);
			}
		break;
		case BS_PUSHED:
			if(READ_BIT(PINB,PB0)==1){
				app_button_state = BS_RELEASING;
				TIMER_start(&app_timer_button,20);
			}
			else{
				TASK_post(&app_task_button);
			}
		break;
	}
}